package com.hi.hiparty.ui.fragment;

import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.app.TimePickerDialog;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.TimePicker;
import android.widget.Toast;

import com.actionbarsherlock.app.SherlockFragment;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.hi.hiparty.R;
import com.hi.hiparty.entity.Party;
import com.hi.hiparty.service.ILocationService;
import com.hi.hiparty.ui.session.UserSessionManager;
import com.hi.hiparty.util.ApiHelper;
import com.hi.hiparty.util.HttpUtil;
import com.hi.hiparty.util.StringUtils;
import com.hi.hiparty.util.TimeUtils;

public class EditPartyFragment extends SherlockFragment implements View.OnClickListener {

	static final private int GET_THEME_CODE = 0;

	public static final String TAG = EditPartyFragment.class.getSimpleName();

	private Button mStartDateView;

	private Button mStartTimeView;

	private Button mLocationEditView;

	private Button mCurrentLabelButton;

	private EditText mEventNameView;

	private EditText mDescriptionView;

	private boolean startTimeSetted = false;

	private Button mSubmitButton;

	private RadioGroup mSexLimitRadioGroup;

	private Party party;

	private ILocationService locationService;

	public void setLocationService(ILocationService locationService) {
		this.locationService = locationService;
	}

	private OnClickEditLocationListener onClickEditLocationListener;

	public void setOnClickEditLocationListener(OnClickEditLocationListener onClickEditLocationListener) {
		this.onClickEditLocationListener = onClickEditLocationListener;
	}

	private OnPubNewPartySuccessListener onPubNewPartySuccessListener;

	public void setOnPubNewPartySuccessListener(OnPubNewPartySuccessListener onPubNewPartySuccessListener) {
		this.onPubNewPartySuccessListener = onPubNewPartySuccessListener;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		party = new Party();
		party.setStartTime(TimeUtils.getDefaultPartyStartTime());
		super.onCreate(savedInstanceState);
		setHasOptionsMenu(true);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		// Inflate the layout for this fragment
		View view = inflater.inflate(R.layout.pub_new_date, container, false);
		mEventNameView = (EditText) view.findViewById(R.id.edit_text_date_title);
		mDescriptionView = (EditText) view.findViewById(R.id.edit_text_description);
		mStartDateView = (Button) view.findViewById(R.id.start_date);
		mStartDateView.setOnClickListener(this);
		mStartTimeView = (Button) view.findViewById(R.id.start_time);
		mStartTimeView.setOnClickListener(this);
		mLocationEditView = (Button) view.findViewById(R.id.location_text);
		mLocationEditView.setOnClickListener(this);
		if (null != party && null != party.getAddress()) {
			mLocationEditView.setText(party.getAddress());
		}
		mSubmitButton = (Button) view.findViewById(R.id.btn_submit_new_party);
		mSubmitButton.setOnClickListener(this);

		mSexLimitRadioGroup = (RadioGroup) view.findViewById(R.id.radio_party_sex_limit);
		mSexLimitRadioGroup.setOnCheckedChangeListener(new PartySexLimitCheckListener());
		mSexLimitRadioGroup.check(R.id.party_limit_none);

		if (null == party.getStartTime() || !startTimeSetted) {
			// mStartDateView.setHint("开始时间:(" +
			// TimeUtils.formatDate(TimeUtils.getDefaultPartyStartTime()) +
			// ")");
			mStartDateView.setHint("选择时间");
			mStartTimeView.setHint(TimeUtils.formatTime(TimeUtils.getDefaultPartyStartTime()));
		} else {
			mStartDateView.setText(TimeUtils.formatDate(party.getStartTime()));
			mStartTimeView.setText(TimeUtils.formatTime(party.getStartTime()));
		}

		String[] partyTitleHints = { "逛街", "逛公园", "打羽毛球", "喝咖啡", "酒吧小酌", "看书", "自习", "学习", "打网球", "桌球", "公园", "滑雪",
				"看电影" };
		for (int i = 0; i < partyTitleHints.length; i++) {
			switch (i % 2) {
			case 0:
				LinearLayout viewGourp = (LinearLayout) view.findViewById(R.id.party_title_hint_list_1);
				Button button = (Button) inflater.inflate(R.layout.btn_pub_party_title_selector, viewGourp, false);
				button.setText(partyTitleHints[i]);
				button.setOnClickListener(new LabelButtonOnClickListener());
				viewGourp.addView(button);
				break;
			case 1:
				viewGourp = (LinearLayout) view.findViewById(R.id.party_title_hint_list_2);
				button = (Button) inflater.inflate(R.layout.btn_pub_party_title_selector, viewGourp, false);
				button.setText(partyTitleHints[i]);
				button.setOnClickListener(new LabelButtonOnClickListener());
				viewGourp.addView(button);
				break;

			default:
				break;
			}
		}

		return view;
	}

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		try {
			onClickEditLocationListener = (OnClickEditLocationListener) activity;
			onPubNewPartySuccessListener = (OnPubNewPartySuccessListener) activity;
		} catch (ClassCastException e) {
			Log.w(TAG, "设置onClickEditLocationListener和onPubNewPartySuccessListener出现异常，部分交互可能无法实现");
		}
	}

	@Override
	public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
		super.onCreateOptionsMenu(menu, inflater);
		getSherlockActivity().getSupportActionBar().setTitle(getString(R.string.ab_title_pub_new_party));
		getSherlockActivity().getSupportActionBar().setDisplayHomeAsUpEnabled(true);
		getSherlockActivity().getSupportActionBar().setHomeButtonEnabled(true);
	}

	@Override
	public boolean onOptionsItemSelected(com.actionbarsherlock.view.MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			getSherlockActivity().getSupportFragmentManager().popBackStack();
			return true;

		default:
			return super.onOptionsItemSelected(item);
		}
	}

	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.start_date:
			DatePickerFragmentDialog startDatePicker = new DatePickerFragmentDialog(
					DatePickerFragmentDialog.TYPE_START_DATE_PICKER);
			startDatePicker.setTargetFragment(this, 0);
			Bundle paramsBundle = new Bundle();
			if (null == party || null == party.getStartTime()) {
				paramsBundle.putLong("date_time", TimeUtils.tomorrow().getTime());
			} else {
				paramsBundle.putLong("date_time", party.getStartTime().getTime());
			}
			startDatePicker.setArguments(paramsBundle);
			startDatePicker.show(getFragmentManager(), "date");
			break;

		case R.id.start_time:
			TimePickerFragmentDialog startTimePicker = new TimePickerFragmentDialog(
					TimePickerFragmentDialog.TYPE_START_TIME_PICKER);
			startTimePicker.setTargetFragment(this, 0);
			paramsBundle = new Bundle();
			if (null == party || null == party.getStartTime()) {
				Calendar cal = Calendar.getInstance();
				cal.set(Calendar.HOUR_OF_DAY, 10);
				cal.set(Calendar.MINUTE, 0);
				paramsBundle.putLong("date_time", cal.getTimeInMillis());
			} else {
				paramsBundle.putLong("date_time", party.getStartTime().getTime());
			}
			startTimePicker.setArguments(paramsBundle);
			startTimePicker.show(getFragmentManager(), "time");
			break;

		case R.id.location_text:
			if (null != onClickEditLocationListener) {
				onClickEditLocationListener.onClickEditLocation();
			}
			break;

		case R.id.btn_submit_new_party:
			submit();
			break;

		case R.id.btn_back:
			getSherlockActivity().getSupportFragmentManager().popBackStack();
			break;

		default:
			break;
		}

	}

	private void submit() {
		if (null == mEventNameView.getText() || StringUtils.isBlank(mEventNameView.getText().toString())) {
			Toast.makeText(getActivity(), "约会标题不能为空", Toast.LENGTH_SHORT).show();
			return;
		}
		if (null == mLocationEditView.getText() || StringUtils.isBlank(mLocationEditView.getText().toString())) {
			Toast.makeText(getActivity(), "约会地址不能为空", Toast.LENGTH_SHORT).show();
			return;
		}
		new SubmitNewPartyTask().execute(party);
	}

	public void onStartDateSet(int year, int monthOfYear, int dayOfMonth) {
		Calendar cal = Calendar.getInstance();
		if (null != party.getStartTime()) {
			cal.setTime(party.getStartTime());
		}
		cal.set(Calendar.YEAR, year);
		cal.set(Calendar.MONTH, monthOfYear);
		cal.set(Calendar.DAY_OF_MONTH, dayOfMonth);
		party.setStartTime(cal.getTime());
		mStartDateView.setText(TimeUtils.formatDate(cal.getTime()));
		startTimeSetted = true;
	}

	public void onStartTimeSet(int hourOfDay, int minute) {
		Calendar cal = Calendar.getInstance();
		if (null != party.getStartTime()) {
			cal.setTime(party.getStartTime());
		}
		cal.set(Calendar.HOUR_OF_DAY, hourOfDay);
		cal.set(Calendar.MINUTE, minute);
		party.setStartTime(cal.getTime());
		mStartTimeView.setText(TimeUtils.formatTime(cal.getTime()));
	}

	public void setLocation(String address, String latlng) {
		party.setAddress(address);
		party.setPartyPos(latlng);
	}

	private class PartySexLimitCheckListener implements OnCheckedChangeListener {

		@Override
		public void onCheckedChanged(RadioGroup group, int checkedId) {

		}

	}

	private class LabelButtonOnClickListener implements OnClickListener {

		@Override
		public void onClick(View v) {
			Button button = (Button) v;
			button.setFocusableInTouchMode(true);
			button.requestFocus();
			if (mCurrentLabelButton != null) {
				// 恢复
				mCurrentLabelButton.setFocusable(false);
				mCurrentLabelButton.setPressed(false);
				mCurrentLabelButton.setFocusableInTouchMode(false);
			}
			mCurrentLabelButton = button;
			mEventNameView.setText(button.getText());
		}
	}

	public static class DatePickerFragmentDialog extends DialogFragment implements DatePickerDialog.OnDateSetListener,
			DialogInterface.OnClickListener {

		public static final int TYPE_START_DATE_PICKER = 0;

		public static final int TYPE_END_DATE_PICKER = 1;

		private boolean mCancelled;

		private int mType = -1;

		public DatePickerFragmentDialog() {
		}

		public DatePickerFragmentDialog(int type) {
			this.mType = type;
		}

		public void onClick(DialogInterface paramDialogInterface, int which) {
			EditPartyFragment pubDateFragment = (EditPartyFragment) getTargetFragment();
			if (which == DialogInterface.BUTTON_NEGATIVE) {
				// pubDateFragment.onEndDateCleared();
			}
		}

		public Dialog onCreateDialog(Bundle bundle) {
			if (this.mType == -1) {
				this.mType = bundle.getInt("type");
				this.mCancelled = bundle.getBoolean("cancelled", this.mCancelled);
			}
			long time = getArguments().getLong("date_time");
			Calendar cal = Calendar.getInstance();
			cal.setTimeInMillis(time);
			DatePickerDialog datePickerDialog = new DatePickerDialog(getActivity(), this, cal.get(Calendar.YEAR),
					cal.get(Calendar.MONTH), cal.get(Calendar.DATE));
			if (this.mType == TYPE_END_DATE_PICKER)
				datePickerDialog.setButton(DialogInterface.BUTTON_NEGATIVE, getString(R.string.dialog_clear), this);
			return datePickerDialog;
		}

		public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
			if (this.mCancelled)
				return;
			if (this.mType == TYPE_START_DATE_PICKER) {
				((EditPartyFragment) getTargetFragment()).onStartDateSet(year, monthOfYear, dayOfMonth);
			} else if (this.mType == TYPE_END_DATE_PICKER) {
				// ((EditPartyFragment) getTargetFragment()).onEndDateSet(year,
				// monthOfYear, dayOfMonth);
			}
		}

		public void onSaveInstanceState(Bundle paramBundle) {
			super.onSaveInstanceState(paramBundle);
			paramBundle.putInt("type", this.mType);
			paramBundle.putBoolean("cancelled", this.mCancelled);
		}
	}

	public static class TimePickerFragmentDialog extends DialogFragment implements TimePickerDialog.OnTimeSetListener,
			DialogInterface.OnClickListener {

		public static final int TYPE_START_TIME_PICKER = 0;

		public static final int TYPE_END_TIME_PICKER = 1;

		private boolean mCancelled;

		private int mType = -1;

		public TimePickerFragmentDialog() {
		}

		public TimePickerFragmentDialog(int paramInt) {
			this.mType = paramInt;
		}

		public void onClick(DialogInterface dialogInterface, int which) {
			EditPartyFragment pubDateFragment = (EditPartyFragment) getTargetFragment();
			if (which == DialogInterface.BUTTON_NEGATIVE) {
				// pubDateFragment.onEndTimeCleared();
			}
		}

		public Dialog onCreateDialog(Bundle paramBundle) {
			if (this.mType == -1) {
				this.mType = paramBundle.getInt("type", -1);
				this.mCancelled = paramBundle.getBoolean("cancelled", this.mCancelled);
			}
			long time = getArguments().getLong("date_time");
			Calendar cal = Calendar.getInstance();
			cal.setTimeInMillis(time);
			TimePickerDialog timePicker = new TimePickerDialog(getActivity(), this, cal.get(Calendar.HOUR_OF_DAY),
					cal.get(Calendar.MINUTE), DateFormat.is24HourFormat(getActivity()));
			if (this.mType == TYPE_END_TIME_PICKER)
				timePicker.setButton(DialogInterface.BUTTON_NEGATIVE, getString(R.string.dialog_clear), this);
			return timePicker;
		}

		public void onSaveInstanceState(Bundle paramBundle) {
			super.onSaveInstanceState(paramBundle);
			paramBundle.putInt("type", this.mType);
			paramBundle.putBoolean("cancelled", this.mCancelled);
		}

		public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
			if (this.mCancelled)
				return;
			if (this.mType == TYPE_START_TIME_PICKER) {
				((EditPartyFragment) getTargetFragment()).onStartTimeSet(hourOfDay, minute);
			} else if (this.mType == TYPE_END_TIME_PICKER) {
				// ((EditPartyFragment)
				// getTargetFragment()).onEndTimeSet(hourOfDay, minute);
			}
		}
	}

	private class SubmitNewPartyTask extends AsyncTask<Party, Void, Boolean> {

		private ProgressDialog dialog;

		private String errorMessage;

		@Override
		protected void onPreExecute() {
			dialog = ProgressDialog.show(EditPartyFragment.this.getActivity(), "", "正在发布活动...", true);
		}

		@Override
		protected Boolean doInBackground(Party... pt) {
			Map<String, String> params = new HashMap<String, String>();
			params.put("theme", null == party.getTheme() ? "theme_001" : party.getTheme());
			params.put("title", mEventNameView.getText().toString());
			params.put("description", mDescriptionView.getText().toString());
			params.put("starttime", TimeUtils.combineDateAndTime(mStartDateView.getText().toString(), mStartTimeView
					.getText().toString()));
			params.put("address", mLocationEditView.getText().toString());
			params.put("partypos", party.getPartyPos());
			params.put("userid", UserSessionManager.getUserSession(getActivity()).getUserid());
			params.put("userpos", UserSessionManager.getUserSession(getActivity()).getLatlng());
			Log.v(TAG, "pulish new date:" + params);
			String resultString = HttpUtil.POST(ApiHelper.API_PUBLISH_PARTY, params);
			Log.v(TAG, "pulish new date result:" + resultString);
			try {
				JSONObject json = new JSONObject(resultString);
				if (json.getInt("success") == 1) {
					return true;
				} else {
					errorMessage = json.getString("error");
					return false;
				}
			} catch (JSONException e) {
				errorMessage = "服务请求格式异常，请稍后再试";
				return false;
			}
		}

		@Override
		protected void onPostExecute(Boolean result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			dialog.cancel();
			if (result) {
				if (null != onPubNewPartySuccessListener) {
					onPubNewPartySuccessListener.onPubNewPartySuccess();
				}
			} else {
				Toast.makeText(getActivity(), errorMessage, Toast.LENGTH_SHORT).show();
			}
		}
	}

	public static interface OnPubNewPartySuccessListener {
		public void onPubNewPartySuccess();
	}

	public static interface OnClickEditLocationListener {
		public void onClickEditLocation();
	}
}
